package com.larsgard.gedviewer.server.ged;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.logging.Logger;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.xml.Unmarshaller;

import com.larsgard.gedviewer.shared.entities.Person;

public class GedParserImplCastor implements GedParser {

    static final Logger log = Logger.getLogger(GedParserImplCastor.class.getName());
    private static String inputSourcePath = "xml/gedsource.xml";
    private static String mappingFilePath = "xml/castorMapping.xml";
    private static ArrayList<Person> family;
    private static int pos = 0;

    @SuppressWarnings("unchecked")
    public GedParserImplCastor(String source, String mapping2) {
	long start = System.currentTimeMillis();
	try {
	    Mapping mapping = new Mapping();
	    File mappingFile = new File(mapping2);
	    mapping.loadMapping(mappingFile.getAbsolutePath());

	    FileReader reader = new FileReader(source);
	    Unmarshaller unmarshaller = new Unmarshaller(ArrayList.class);
	    unmarshaller.setMapping(mapping);
	    family = (ArrayList<Person>) unmarshaller.unmarshal(reader);
	    reader.close();
	    log.info("Read " + family.size() + " persons.");
	} catch (Exception e) {
	    log.severe("Exception occured when initializing " + this.getClass().getName() + ".");
	}
	long stop = System.currentTimeMillis();
	log.info("Spent millis in creating " + this.getClass().getName() + " : " + (stop - start));

    }

    public GedParserImplCastor() {
	this(inputSourcePath, mappingFilePath);
    }

    @Override
    public Boolean hasNext() {
	System.out.println("pos" + pos);
	System.out.println("family" + family.size());
	return (pos <= (family.size() - 1));
    }

    @Override
    public Person read() throws Exception {

	return family.get(pos++);
    }

    public Person read(int pos) {
	if (pos % 10 == 0) {
	    log.severe("Pos is " + pos);
	}
	GedParserImplCastor.pos = pos;
	return family.get(pos);
    }

    public void setMappingFile(String string) {
	mappingFilePath = string;
    }

    public void setInputFile(String string) {
	inputSourcePath = string;
    }

}
